package com.wzy.server.config;


import com.wzy.server.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

//websocket配置类
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Value("{jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserDetailsService userDetailsService;

//    添加这个endpoint端点，这样在网页可以通过websocket连接上服务
//    也就是我们配置websocket的服务器地址，并且可以指定是否使用socketJS
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
//      1.添加端点            2.将路径注册为stop端点，用户连接这个端点就可以进行websocket通讯3.允许跨境（所有）4.支持socketJS访问
        registry.addEndpoint("/ws/ep").setAllowedOrigins("*").withSockJS();
    }

//    输入通道的配置（在jwt令牌下才用配置）
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {

        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {//预发送
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
//               判断是否为连接，如果是，需要获取token，并且设置用户对象
                if (StompCommand.CONNECT.equals(accessor.getCommand())){
//                    获取token                                               从前端获取
                    String token = accessor.getFirstNativeHeader("Auth-Token");
                    if (!StringUtils.isEmpty(token)){//token是否为空
                        String authToken = token.substring(tokenHead.length());//获取token
                        String userName = jwtTokenUtil.getUserNameFormToken(authToken);//获取用户名
                        if (!StringUtils.isEmpty(userName)){//用户名是否为空
                            UserDetails userDetails = userDetailsService.loadUserByUsername(userName);//登录
                            if (jwtTokenUtil.validateToken(authToken,userDetails)){//验证token是否有效，重新设置用户对象
                                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());//重新设置token
                                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                                accessor.setUser(authenticationToken);
                            }
                        }
                    }
                }
                return message;
            }
        });
    }

//    配置消息代理
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
//        配置代理域，可以配置多个，配置代理目地的前缀/queue，可以在配置域上向客户端推送消息
        registry.enableSimpleBroker("/queue");
    }
}
